package com.example.AiLangLearn.asr;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import com.example.AiLangLearn.R;
import com.example.AiLangLearn.adapter.SpinnerAdapter;
import com.iflytek.sparkchain.core.asr.ASR;
import com.iflytek.sparkchain.core.asr.AsrCallbacks;
import com.iflytek.sparkchain.core.asr.AudioAttributes;
import com.iflytek.sparkchain.core.asr.Segment;
import com.iflytek.sparkchain.core.asr.Transcription;
import com.iflytek.sparkchain.core.asr.Vad;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;

public class AsrMultilingualDemoActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "AEELog";
    private TextView tv_result;
    private Spinner mTypeSpinner;
    private String filePath;
    private ASR asr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asr_mul);
        initView();
        initASR();
    }





    AsrCallbacks mAsrCallbacks = new AsrCallbacks() {
        @Override
        public void onResult(ASR.ASRResult asrResult, Object o) {
            String result = asrResult.getBestMatchText();
            int status = asrResult.getStatus();
            String sid     = asrResult.getSid();
            List<Vad> vads = asrResult.getVads();
            List<Transcription> transcriptions = asrResult.getTranscriptions();
            int vad_begin = -1;
            int vad_end = -1;
            String word = null;
            for(Vad vad:vads){
                vad_begin = vad.getBegin();
                vad_end = vad.getEnd();
            }
            for(Transcription transcription : transcriptions){
                List<Segment> segments = transcription.getSegments();
                for(Segment segment:segments){
                    word = segment.getText();
                }
            }
            String resultBuf = "onResult:{result:"+result+",status:"+status+",begin:"+vad_begin+",end:"+vad_end+",word:"+word+"}";
            Log.d(TAG,resultBuf);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_result.append(resultBuf);
                }
            });
        }

        @Override
        public void onError(ASR.ASRError asrError, Object o) {
            int errCode   = asrError.getCode();
            String errMsg = asrError.getErrMsg();
            String sid    = asrError.getSid();
        }
    };

    private void initASR(){
        asr = new ASR("mul_cn","slm","mandarin");
//        asr = new ASR("zh_cn","slm","mandarin");
        asr.registerCallbacks(mAsrCallbacks);
    }

    private void initView() {
        mTypeSpinner = findViewById(R.id.asr_language_spinner_mul);
        tv_result = findViewById(R.id.asr_tv_result_mul);
        findViewById(R.id.asr_btn_sptrans_mul).setOnClickListener(this);
        findViewById(R.id.asr_btn_cancel_mul).setOnClickListener(this);
        SpinnerAdapter typeSpinner = new SpinnerAdapter(this,  AsrMultilingualDemoParams.getTypes());
        mTypeSpinner.setAdapter(typeSpinner);
        mTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                filePath = AsrMultilingualDemoParams.getTypes().get(position).value;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private int testAsr(String path) {
        int ret = -1;
        if(asr == null){
            Log.d(TAG, "Asr 初始化失败。");
            return ret;
        }
        AudioAttributes atr = new AudioAttributes();
        atr.setSampleRate(16000);
        atr.setEncoding("raw");
        atr.setChannels(1);
        ret = asr.start(atr, null);
        if (ret != 0) {
            Log.e(TAG, "asr start failed" + ret);
            return ret;
        }
        try{
            Log.d(TAG,"ready load audio:"+path);
            byte[] data = readStream(path);
            int leftAudioBytes = data.length;
            int byteWrites = 1280;
            int writeLen = 0;
            int index = 0;

            while (leftAudioBytes > 0) {
                if (leftAudioBytes > byteWrites) {
                    writeLen = byteWrites;
                } else {
                    writeLen = leftAudioBytes;
                }
                leftAudioBytes -= writeLen;
                byte[] part = Arrays.copyOfRange(data, index * byteWrites,
                        index * byteWrites + writeLen);

                ret = asr.write(part);
                if (ret != 0) {
                    Log.e(TAG, "asr write failed" + ret);
                    return ret;
                }
                index++;
            }
            ret = asr.stop(false);//不报错结束
        }catch(Exception e){
            e.printStackTrace();
            ret = asr.stop(true);//报错打断
        }
        if (ret != 0) {
            Log.e(TAG, "asr stop failed" + ret);
            return ret;
        }
        return ret;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(asr!=null)
            asr.stop(true);//报错打断
    }

    private void cancel(){
        if(asr!=null)
            asr.stop(true);//报错打断
    }

    public byte[] readStream(String filePath) throws Exception {
        FileInputStream fs = new FileInputStream(filePath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.asr_btn_sptrans_mul:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if(asr == null || filePath == null){
                            Log.e(TAG,"start testAsr fail! asr="+asr+",filePath="+filePath);
                        }
                        int ret = testAsr(filePath);
                        if(ret!=0){
                            Log.e(TAG,"start testAsr fail:"+ret);
                        }
                    }
                }).start();
                break;
            case R.id.asr_btn_cancel_mul:
                cancel();
                break;
        }
    }



}